import React, { Component } from 'react'
import { Card } from 'antd'
import { connect } from 'react-redux'
import '../../less/index.less'
import { withRouter } from 'react-router-dom'
import TaskContentBox from './task-content-box'
import * as taskActions from '../../actions/task'
import FlipPages from '../common/flip-pages'
import { FormattedMessage } from 'react-intl'

class Task extends Component {
  constructor (props) {
    super(props)
    this.state = {
      showFeedbackInput: false,
      taskId: -1,
      programId: -1
    }
  }

  componentDidMount () {
    this.setState({
      taskId: this.props.match.params.taskId,
      programId: this.props.match.params.programId
    }, () => {
      this.props.getTask(this.state.taskId)
      this.props.getFlipTask(this.state.taskId)
    })
  }

  flipTask (type) {
    const { flipIds, history } = this.props
    const { programId } = this.state
    const currentId = type === 'next' ? flipIds.nextId : flipIds.previousId
    this.props.getTask(currentId)
    this.props.getFlipTask(currentId)
    this.setState({taskId: currentId})
    history.push(`/program/${programId}/task/${currentId}`)
  }

  render () {
    const { task } = this.props.taskInfo
    const { flipIds } = this.props
    const link = <a target='_blank' href={task.link}><FormattedMessage id='论坛答疑' /></a>
    return <Card title={task.title} bordered={false} extra={link}>
      <TaskContentBox task={task}
        getTask={this.props.getTask} />
      <FlipPages flipTask={this.flipTask.bind(this)} flipIds={flipIds} />
    </Card>
  }
}

const mapStateToProps = ({ taskInfo, flipPages }) => ({
  taskInfo, flipIds: flipPages
})
const mapDispatchToProps = dispatch => ({
  getTask: (taskId) => dispatch(taskActions.getTask(taskId)),
  getFlipTask: (taskId) => dispatch(taskActions.getFlipTask(taskId))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Task))
